#pragma once

#include <string>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>

#define _DEBUG

#define NS_NAME				fooking
#define NS_BEGIN			namespace NS_NAME{
#define NS_END				}
#define NS_USING			using namespace NS_NAME

#define zmalloc				malloc
#define zfree				free
#define zrealloc			realloc

#define PROTOCOL_RAW		1
#define PROTOCOL_FASTCGI	2

#define SOCKET_NONE			0
#define SOCKET_TCP			1
#define SOCKET_UNIX			2

#define SID_LENGTH			20
#define SID_FULL_LEN		21

/* Anti-warning macro... */
#define NOTUSED(V) 			((void) V)

NS_BEGIN
	//base class
	class Object
	{
	public:
		Object(){}
		virtual ~Object(){}
	};
	
	typedef unsigned char	uint_8;
	typedef unsigned short	uint_16;

	//socket类型
	typedef struct{
		int		type;
		union{
			struct{
				short		tcp_port;
				char		tcp_host[58];
			};
			struct{
				char		unix_name[60];
			};
		};
	}SocketOption;
	
	namespace net{
		inline short readNetInt16(const char *ptr)
		{
			short n = ((unsigned char)ptr[0] << 8) | (unsigned char)ptr[1];
			return n;
		}

		inline int readNetInt32(const char *ptr)
		{
			int n = (((unsigned char)ptr[0] & 0x7F) << 24) | 
					((unsigned char)ptr[1] << 16) | 
					((unsigned char)ptr[2] << 8) | 
					(unsigned char)ptr[3];
			return n;
		}

		inline void writeNetInt16(char *ptr, short n)
		{
			ptr[0] = (n >> 8) & 0xFF;
			ptr[1] = n & 0xFF;
		}

		inline void writeNetInt32(char *ptr, int n)
		{
			ptr[0] = (n >> 24) & 0x7F;
			ptr[1] = (n >> 16) & 0xFF;
			ptr[2] = (n >> 8) & 0xFF;
			ptr[3] = n & 0xFF;
		}
	}
	
	namespace utils{
		inline SocketOption parseSocket(const char *string)
		{
			char *str = (char*)string;
			int len = strlen(string);
			SocketOption opt;
			memset(&opt, 0, sizeof(SocketOption));
			
			if(strncmp(str, "unix:", 5) == 0){//unix
				opt.type = SOCKET_UNIX;
				memcpy(opt.unix_name, str + 5, len - 5);
				return opt;
			}
			
			//tcp tok
			int pos = 0;
			if(strncmp(str, "tcp://", 6) == 0){
				pos = 6;
			}
			
			char *sep = strchr(str + pos, ':');
			if(!sep){
				return opt;
			}
			
			//host length
			int nhost = sep - str + pos;
			
			//port
			int port = atoi(sep + 1);
			if(port < 1){
				return opt;
			}
			
			opt.type = SOCKET_TCP;
			opt.tcp_port = port;
			memcpy(opt.tcp_host, str + pos, nhost);
			
			return opt;
		}
		
		inline int randInt(int a, int b)
		{
			if(a == b){
				return a;
			}else if(a > b){
				int t = a;
				a = b;
				b = t;
			}
			int n = b - a + 1;
			return rand() % n + a;
		}
		
		inline void setProcTitle(char **argv, const char *title)
		{
			char *p = argv[0];
			int tlen = strlen(title);
			strncpy(p, title, tlen);
			p[tlen] = '\0';
		}
	}
NS_END